package com.kaifamiao.month04.day05;

public class MyLinkedList {

    private Node first;
    private Node last;
    private int count;

    public void addFirst(Object obj) {
        Node node = new Node(obj, first);
        if (first == null) {
            last = node;
        }
        first = node;
        count++;
    }

    public void addLast(Object obj) {
        Node node = new Node(obj, null);
        if (last == null) {
            first = node;
        } else {
            last.setNext(node);
        }
        last = node;
        count++;
    }

    public void add(Object obj) {
        addLast(obj); // 默认在末尾添加元素
    }

    public void add(int index, Object obj) {
        if (checkIndex(index)) {
            if (index == 1) addFirst(obj);
            else if (index == count + 1) addLast(obj);
            else {
                Node node = getNode(index - 1); // 当前位置的前一个元素
                Node next = node.getNext(); // 下一个元素
                Node current = new Node(obj, next);
                node.setNext(current);
                count++;
            }
        } else
            System.err.println("输入正确的位置！");
    }

    private boolean checkIndex(int index) {
        return index <= count + 1;
    }

    public int size() {
        return count;
    }

    public Object getFirst() {
        return first.getValue();
    }

    public Object getLast() {
        return last.getValue();
    }

    public Object get(int index) {
        return getNode(index).getValue();
    }

    private Node getNode(int index) {
        Node node = first;
        for (int i = 1; i < index; i++) {
            node = node.getNext();
        }
        return node;
    }

    // 开头移除元素
    public Object removeFirst() {
        if (first == null) {
            return null;
        } else {
            Node f = first;
            Node next = first.getNext();
            first = next;
            if (next == null)
                last = null;
            count--;
            return f.getValue();
        }
    }

    public Object removeLast() {
        if (last == null) {
            return null;
        } else {
            Node l = last;
            Node prev = getNode(count - 1);
            prev.setNext(null);
            last = prev;
            count--;
            return l.getValue();
        }
    }

    public Object remove(int index) {
        if(checkIndex(index)){
            if(index == 1) return removeFirst();
            else if (index == count - 1) return removeLast();
            else {
                Node node = getNode(index);
                Node prev = getNode(index - 1);
                prev.setNext(node.getNext());
                node.setNext(null);
                count --;
                return node;
            }
        }else{
            System.out.println("输入正确的位置！");
            return -1;
        }
    }
}
